package com.lagou.rpc.zk;

import com.lagou.rpc.config.ZookeeperConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * @Author Liu Chang
 * @Date 2021/10/19 1:45 上午
 */
public class ZKApi {


    private static CuratorFramework client = ZookeeperConfig.zkClient();


    public static void createNode(String path, String content) {
        try {
            client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL).forPath(path, content.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("success create znode"+path);
    }

    public static List<String> getChildrenNodes(String path) throws Exception {
        return (List<String>) client.getChildren().forPath(path);
    }

    public static String getNodeContent(String path) throws Exception {
        Stat stat = new Stat();
        byte[] bytes = client.getData().storingStatIn(stat).forPath(path);
        return new String(bytes);
    }

    public static void setNodeContent(String path, String content) throws Exception {
        Stat stat = new Stat();
        client.setData().withVersion(stat.getVersion()).forPath(path, content.getBytes());
    }
}
